# -*-coding:utf-8 -*-
# -*-coding:utf-8 -*-
import time
from datetime import datetime, timedelta, timezone

from pymongo import MongoClient

from .. import config
from ..xz_handler.base import XZBaseHandler


class GPSMongoHandler(XZBaseHandler):

    def __init__(self, *args, **kwargs):
        self.connect = MongoClient(config.MONGO['URL'])
        self.db = self.connect.get_database(config.DB)
        self.time_range = {
        }
        super().__init__(*args, **kwargs)

    def handle(self, data):
        vehicle_id = self.map2new_vehicle_id(data['vehicleId'])
        if vehicle_id is None:
            return
        appLocations = data['appLocations']
        if data["vehicleId"] not in self.vin2vehicle_map:
            self.logger.warning(f'vehicle_id={vehicle_id} old_vehicle_id={data["vehicleId"]}')
            return

        if vehicle_id not in self.time_range:
            start_time = datetime.strptime(appLocations[0]['locationTime'], "%Y-%m-%d %H:%M:%S")
            self.time_range[vehicle_id] = {
                'data': {
                    "device_imei":  self.vin2vehicle_map[data['vehicleId']]['imei'],
                    "gps": [],
                    "meta": {
                        "version": 0.1,
                        "provider": "xiao-zhuo"
                    },
                    "vehicle_license_number": self.vin2vehicle_map[data['vehicleId']]['license_number'],
                },
                'start_time': start_time,
                'end_time': start_time + timedelta(minutes=5),
            }

        for row in appLocations:
            gps_point = {"altitude": float(row['altitude']),
                         "longitude": float(row['gpsLat']),
                         "latitude": float(row['gpsLon']),
                         "direction": float(row['bearing']),
                         "speed": float(row['speed']),
                         "occurred_time": datetime.strptime(row['locationTime'], "%Y-%m-%d %H:%M:%S")
                         }
            if gps_point['occurred_time'] > self.time_range[vehicle_id]['end_time']:
                self.insert_to_mongo(self.time_range[vehicle_id]['data'])
                start_time = self.time_range[vehicle_id]['start_time']
                self.time_range[vehicle_id]['start_time'] = start_time + timedelta(minutes=5)
                self.time_range[vehicle_id]['end_time'] = start_time + timedelta(minutes=10)
            self.time_range[vehicle_id]['data']['gps'].append(gps_point)
